<?php
/**
 * @version		$Id: updatedata.php 10381 2008-10-01 03:35:53Z yopensource $
 * @package		YOS
 * @subpackage	Update Data
 * @author 		yopensource (yopensource@gmail.com)
 * @copyright	Copyright (C) 2005 - 2008 YOS. All rights reserved.
 * @license		Commercial
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport('joomla.application.component.model');

require_once(JPATH_COMPONENT.DS.'classes'.DS.'job.php');


// Set the table directory
//JTable::addIncludePath(JPATH_COMPONENT.DS.'tables');

/**
 * 
 *
 * @package		YOS
 * @subpackage	Update
 * @since 1.5
 */
JTable::addIncludePath(JPATH_COMPONENT_SITE.DS.'cms'.DS.'drupalpost'.DS.'tables');
class YOS_NewsModelWorks extends JModel
{
	//component global configure:
  	//Licens, error...
  	private $_global_configure;
	
  	//to store list of todo jobs
  	private $_arr_jobs = array();
  	
	public function __construct(){
		parent::__construct();
		
		$config 		= &JComponentHelper::getParams('com_yos_news_crawler');
		$this->_global_configure = $config;		
	}
	
	
	/**
	 * perform do all available jobs
	 *
	 * @return boolen
	 */
	public function works(){
		global $mainframe;
		if(JRequest::getInt('debug')){
			@error_reporting(E_ALL);
		}
		
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] check authorize BEGIN"); }
		if(!$this->_authorize()){
			$this->setError('[WORK] #1: Invalid update code');
			return false;
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] check authorize END"); }
		
		//get jobs
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] get list of jobs BEGIN"); }
		if (!$this->_get_jobs()) {
			$this->setError('[WORK] #2: Can not get list of jobs');
			return false;
		}
		
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] get list of jobs END"); }
		
		if (!count($this->_arr_jobs)) {
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] empty jobs."); }
			return true;
		}
		
		//clean tmp dir
		if ($this->_clean_tmp_dir() === false) {
			return false;
		}
		
		//do jobs
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] do jobs BEGIN"); }
		if (!$this->_do_jobs()) {
			$this->setError('[WORK] #3: Do jobs fail');
			return false;
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] do jobs END"); }
	
		return true;
	}
	
	/**
	 * Clean the temp dir which store images received
	 *
	 * @return boolean.
	 */
	private function _clean_tmp_dir(){
		$config =& JFactory::getConfig();
		$tmp_path = $config->getValue('config.tmp_path').DS.'yos_news_crawler';
		
		if (JFolder::exists($tmp_path) === false) {
			return true;
		}
		
		if (JFolder::delete($tmp_path) === false) {
			$this->setError('[WORK] #4: Unable to delete temp directory: '. $tmp_path);
			return false;
		}
		
		if (JFolder::create($tmp_path) === false) {
			$this->setError('[WORK] #5: Unable to create temp directory: '. $tmp_path);
			return false;
		}
		
		return true;
	}
	
	/**
	 * check update code
	 *
	 * @return boolen
	 */
	private function _authorize(){
		//validate update code
		$config = $this->_global_configure;
		
		$code_update	= JRequest::getString('code');
		$config_code	= $config->get('code_update');		
		if (trim($config_code) != trim($code_update)) {			
			return false;
		}
		return true;
	}
	
	/**
	 * Get list of job tobe updated
	 *
	 * @return boolen
	 */
	private function _get_jobs(){		
		global $mainframe;
		if($this->_arr_jobs) return $this->_arr_jobs;
		
		$db	=& JFactory::getDBO();		
		$now	= JHTML::_('date','','%Y-%m-%d %H:%M:%S');
	
		// get job if published and is checkout or not checkout but checked_out_time>now;
		$query="SELECT `id`, `last_update`, `time_update`,`title`,`cms`,`checked_out`
				FROM `#__yos_news_crawler_jobs` 
				WHERE published = 1 and (checked_out=0 or (checked_out<>0 and `checked_out_time` <= ".$db->Quote($now).")) 
				ORDER BY `last_update`
				LIMIT 0,2";
		$db->setQuery($query);
		$time_now		= JHTML::_('date','','%Y-%m-%d %H:%M:%S');
		
		$jobs = $db->loadObjectList();
		
			
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[WORK] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error[0]['file']."\n LINE: ".$arr_error[0]['line']);
			return false;
		}
		
		if (!count($jobs)) {
			$this->setError('[WORK] There is not any job in database');
			return false;
		}
			$ip				=	$_SERVER['REMOTE_ADDR'];
			$fp = fopen( JPATH_COMPONENT_SITE.DS.'models'.DS.'log_work.txt', 'a');
			fputs($fp, "__________________________________________________\r\n");
			fputs($fp, "__________________________________________________\r\n");
			fputs($fp, "--------------------------------------------------\r\n");
			fputs($fp, "------Run time: $time_now ------\r\n");
			fputs($fp, "------From IP: $ip ------\r\n");
			$count	=	count($jobs);
			fputs($fp, "------Total jobs: $count ------\r\n");
		$dem	=	0;
		
		for ($i = 0; $i < count($jobs);$i++){	
				
			if (strtotime($jobs[$i]->last_update) + intval($jobs[$i]->time_update)*60 < strtotime($time_now)) {				
				$obj_jobs = new YOS_Job($jobs[$i]->id);
				array_push($this->_arr_jobs, $obj_jobs);
				
				$checked_out_time	=	$obj_jobs->get('checked_out_time',0);				
				$txt	=	'id: '.$jobs[$i]->id.
							"\t|| Run:TRUE __".
							"\t|| title:".$jobs[$i]->title.
							"\t|| cms:".$jobs[$i]->cms.
							"\t|| c kout:".$jobs[$i]->checked_out.
							"\t|| c_out_time:".$checked_out_time.
							"\t|| l update:".$jobs[$i]->last_update.
							"\t|| t update:".$jobs[$i]->time_update;	
				$dem= $dem + 1;		
			}
			else {
				$txt	=	'id: '.$jobs[$i]->id.
							"\t|| Run:FALSE".	
							"\t|| title:".$jobs[$i]->title.
							"\t|| cms:".$jobs[$i]->cms.
							"\t|| c kout:".$jobs[$i]->checked_out.
							"\t|| l update:".$jobs[$i]->last_update.
							"\t|| t update:".$jobs[$i]->time_update;	
			}		
			fputs($fp, "\t\t $txt \r\n");
			
		}
		fputs($fp, "------Total job being run: $dem \r\n");
		fclose($fp);		
		return true;
	}

	/**
	 * Execute jobs
	 *
	 * @return boolen
	 */
  	private function _do_jobs()
  	{
  		global $mainframe;
  		$config 		= &JComponentHelper::getParams('com_yos_news_crawler');
		$config_code	= $config->get('code_update');
		$config_error	= $config->get('max_error',10);
		$config_percent	= $config->get('percentage',80);

		$MailFrom	= $mainframe->getCfg('mailfrom');
		$FromName	= $mainframe->getCfg('fromname');
		$SiteName	= $mainframe->getCfg('sitename');  		
  		for ($i=0;$i<count($this->_arr_jobs);$i++)
  		{
  			$job =& $this->_arr_jobs[$i];
  			if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] do job BEGIN: <b>".$job->get_job_title()."</b>"); }
  			$job->exec();  			
  			$job->update_job();
  			if (JRequest::getInt('debug')) { YOS_utility::print_debug(1, "[WORK] do job END."); }
  			$arr_error = $job->getErrors();
  			if ($arr_error) {
  				foreach ($arr_error as $str_error){
  					$this->setError($str_error);
  				}
  			}
  		}
  		$return = true;
  		return $return;
  	}
}
